<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * This is a sample module for PyroCMS
 *
 * @author 		Jerel Unruh - PyroCMS Dev Team
 * @website		http://unruhdesigns.com
 * @package 	PyroCMS
 * @subpackage 	Sample Module
 */
class Admin extends Admin_Controller
{
	protected $section = 'news';
	public function __construct()
	{
		parent::__construct();
		// Load all the required classes
		$this->load->library('form_validation');
		
		$this->load->model('escort_news_categories_m');
		$this->load->model('escort_news_m');
		$this->lang->load('news');
		// Set the validation rules
		$this->validation_rules = array(
			array(
				'field' => 'title',
				'label' => 'lang:escort_news_title_label',
				'rules' => 'trim|max_length[255]|required'
			),
			array(
				'field' => 'slug',
				'label' => 'lang:escort_news_slug_label',
				'rules' => 'trim|max_length[255]|alpha_dash|required|callback__check_code'
			),
			array(
				'field'	=> 'language_id',
				'label'	=> 'lang:escort_news_language_label'
			),
			array(
				'field'	=> 'site_ref',
				'label'	=> 'lang:escort_news_site_label'
			),
			array(
				'field'	=> 'category_id',
				'label'	=> 'lang:escort_news_category_label'
			),
			array(
				'field'	=> 'order',
				'label'	=> 'lang:escort_news_order_label',
				'rules' => 'trim|max_length[5]|integer'
			),
			array(
				'field' => 'status',
				'rules' => 'trim|required'
			),
			array(
				'field' => 'news',
				'label' => 'lang:escort_news_news_label',
				'rules' => 'trim|required'
			)
		);

		$this->data->languages = array();
		$languageEntity = new CI_Language_entity();
		
		if ($languages = $languageEntity->getLanguageList())
		{
			foreach ($languages as $language)
			{
				$this->data->languages[$language->id] = $language->language;
			}
		}
		
		$this->data->sites = array();
		$siteEntity = new CI_Site_entity();
		if ($sites = $siteEntity->getSiteList())
		{
			foreach ($sites as $site)
			{
				$this->data->sites[$site->ref] = $site->name;
			}
		}
		
		$this->data->categories = array();
		if ($categories = $this->escort_news_categories_m->order_by('category')->get_all())
		{
			foreach ($categories as $category)
			{
				$this->data->categories[$category->id] = $category->category;
			}
		}
			
				
		$this->template->set_partial('shortcuts', 'admin/partials/shortcuts')
						->append_metadata(js('escort.news.js', 'news'))
						->append_metadata(css('escort.news.css', 'news'));
	}

	/**
	 * List all items
	 */
	public function index()
	{
		//set the base/default where clause
		$base_where = array('status' => 'all');

		//add post values to base_where if f_module is posted
		$base_where = $this->input->post('f_language') ? $base_where + array('language' => $this->input->post('f_language')) : $base_where;
		
		$base_where = $this->input->post('f_site') ? $base_where + array('site' => $this->input->post('f_site')) : $base_where;
		
		$base_where = $this->input->post('f_category') ? $base_where + array('category' => $this->input->post('f_category')) : $base_where;

		$base_where['status'] = $this->input->post('f_status') ? $this->input->post('f_status') : $base_where['status'];

		$base_where = $this->input->post('f_keywords') ? $base_where + array('keywords' => $this->input->post('f_keywords')) : $base_where;

		// Create pagination links
		$total_rows = $this->escort_news_m->count_by($base_where);
		$pagination = create_pagination('admin/news/index', $total_rows);

		// Using this data, get the relevant results
		$news = $this->escort_news_m->limit($pagination['limit'])->get_many_by($base_where);

		//do we need to unset the layout because the request is ajax?
		$this->input->is_ajax_request() ? $this->template->set_layout(FALSE) : '';

		$this->template
			->title($this->module_details['name'])
			->append_metadata(js('admin/filter.js'))
			->set('pagination', $pagination)
			->set('news', $news);

		$this->input->is_ajax_request() ? $this->template->build('admin/tables/posts', $this->data) : $this->template->build('admin/index', $this->data);
			
	}
	
	public function create()
	{
		$this->form_validation->set_rules($this->validation_rules);

		
		$created_time = time();
		

		if ($this->form_validation->run())
		{
			$order = $this->input->post('order');
			if(!$order){
				$order = 0;
			}
			
			$escortNewsEntity = new CI_Escort_news_entity();
			$escortNewsEntity->setTitle($this->input->post('title'));
			$escortNewsEntity->setSlug(strtolower($this->input->post('slug')));
			$escortNewsEntity->setLanguageId($this->input->post('language_id'));
			$escortNewsEntity->setCategoryId($this->input->post('category_id'));
			$escortNewsEntity->setOrder($order);
			$escortNewsEntity->setNews($this->input->post('news'));
			$escortNewsEntity->setStatus($this->input->post('status'));
			$escortNewsEntity->setCreatedTime($created_time);
			$escortNewsEntity->setSiteRef($this->input->post('site_ref'));
			$id = $escortNewsEntity->save();
			if ($id)
			{
				$ci = &get_instance();
				do_log(LOG_ACTION_BACKEND, 0, $ci->ion_auth->get_user()->username, 'escort_log_create_news_action', array($id));
				$this->session->set_flashdata('success', sprintf($this->lang->line('blog_post_add_success'), $this->input->post('title')));
			}
			else
			{
				$this->session->set_flashdata('error', $this->lang->line('blog_post_add_error'));
			}
			$this->input->post('btnAction') == 'save_exit' ? redirect('admin/news') : redirect('admin/news/edit/' . $id);
		}
		else
		{
			// Go through all the known fields and get the post values
			foreach ($this->validation_rules as $key => $field)
			{
				$post->$field['field'] = set_value($field['field']);
			}
			$post->created_time = $created_time;
		}

		$this->template
			->title($this->module_details['name'], lang('escort_news_create_title'))
			->append_metadata($this->load->view('fragments/wysiwyg', $this->data, TRUE))
			->append_metadata(js('jquery/jquery.tagsinput.min.js'))
			->append_metadata(js('blog_form.js', 'blog'))
			->append_metadata(css('jquery/jquery.tagsinput.css'))
			->set('post', $post)
			->build('admin/form');
	}
	public function edit($id = 0)
	{
		$id OR redirect('admin/news');
	
		$post = $this->escort_news_m->get($id);
			
		$created_time = $post->created_time;
		
		$this->form_validation->set_rules(array_merge($this->validation_rules, array(
			
			'slug' => array(
				'field' => 'slug',
				'label' => 'lang:escort_news_slug_label',
				'rules' => 'trim|max_length[255]|alpha_dash|required|callback__check_code['.$id.']'
			)
		)));
	
		if ($this->form_validation->run())
		{
	
			$order = $this->input->post('order');
			if(!$order){
				$order = 0;
			}
			$result = $this->escort_news_m->update($id, array(
					'title'				=> $this->input->post('title'),
					'slug'				=> strtolower($this->input->post('slug')),
					'category_id'		=> $this->input->post('category_id'),
					'order'		=> $order,
					'language_id'		=> $this->input->post('language_id'),
					'site_ref'		=> $this->input->post('site_ref'),
					'news'				=> $this->input->post('news'),
					'status'			=> $this->input->post('status'),
					'created_time'		=> $created_time
			));
				
			if ($result)
			{
				$ci = &get_instance();
				do_log(LOG_ACTION_BACKEND, 0, $ci->ion_auth->get_user()->username, 'escort_log_edit_news_action', array($id));
				$this->session->set_flashdata(array('success' => sprintf(lang('escort_news_edit_success'), $this->input->post('title'))));
			}
				
			else
			{
				$this->session->set_flashdata('error', $this->lang->line('escort_news_edit_error'));
			}
	
			// Redirect back to the form or main page
			$this->input->post('btnAction') == 'save_exit' ? redirect('admin/news') : redirect('admin/news/edit/' . $id);
		}
	
		// Go through all the known fields and get the post values
		foreach ($this->validation_rules as $key => $field)
		{
			if (isset($_POST[$field['field']]))
			{
				$post->$field['field'] = set_value($field['field']);
			}
		}
		$post->type = 'wysiwyg-advanced';
		$this->template
		->title($this->module_details['name'], sprintf(lang('escort_news_edit_title'), $post->title))
		->append_metadata($this->load->view('fragments/wysiwyg', $this->data, TRUE))
		->append_metadata(js('jquery/jquery.tagsinput.min.js'))
		->append_metadata(js('blog_form.js', 'blog'))
		->append_metadata(css('jquery/jquery.tagsinput.css'))
		->set('post', $post)
		->build('admin/form');
	}
	public function delete($id = 0)
	{
		// Delete one
		$ids = ($id) ? array($id) : $this->input->post('action_to');
	
		// Go through the array of slugs to delete
		if ( ! empty($ids))
		{
			$post_titles = array();
			foreach ($ids as $id)
			{
				// Get the current page so we can grab the id too
				if ($post = $this->escort_news_m->get($id))
				{
					$this->escort_news_m->delete($id);
					$ci = &get_instance();
					do_log(LOG_ACTION_BACKEND, 0, $ci->ion_auth->get_user()->username, 'escort_log_delete_news_action', array($id));
					// Wipe cache for this model, the content has changed
					$this->pyrocache->delete('escort_news_m');
					$post_titles[] = $post->title;
				}
			}
		}
	
		// Some pages have been deleted
		if ( ! empty($post_titles))
		{
			// Only deleting one page
			if (count($post_titles) == 1)
			{
				$this->session->set_flashdata('success', sprintf($this->lang->line('escort_news_delete_success'), $post_titles[0]));
			}
			// Deleting multiple pages
			else
			{
				$this->session->set_flashdata('success', sprintf($this->lang->line('escort_news_mass_delete_success'), implode('", "', $post_titles)));
			}
		}
		// For some reason, none of them were deleted
		else
		{
			$this->session->set_flashdata('notice', lang('escort_news_delete_error'));
		}
	
		redirect('admin/news');
	}
	public function _check_code($code, $id = null)
	{
		$language_id = $this->input->post('language_id');
		$this->form_validation->set_message('_check_code', lang('escort_news_already_exist_error'));
		if($id){
			$this->escort_news_m->where('id !=', $id);
		}
		$this->escort_news_m->where('language_id =', $language_id);
		
		if($this->escort_news_m->get_by('slug',$code)){
			return false;
		}else{
			return true;
		}
	}
}
